/**
 * 常用方法封装 请求，文件上传等
 * @author echo. 
 **/
import {getToken} from './auth'
const tui = {
	//接口地址
	interfaceUrl: function() {
		// return 'http://192.168.1.101:8083/doudougou' //本地
		return 'https://youpindou.com:8083/doudougou' // 测试版
		// return 'https://youpindou.com:8063/doudougou' // 正式版
	},
	interfaceUrls: function() {
		// return 'http://192.168.1.101:8080/miniProgram' //本地
		return 'https://youpindou.com:8080/miniProgram' // 测试版
		// return 'https://youpindou.com/miniProgram' // 正式版
	},
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param string method 请求方式
	 *  GET or POST
	 * @param {*} postData 请求参数
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool isForm 数据格式
	 *  true: 'application/x-www-form-urlencoded'
	 *  false:'application/json'
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 * @param bool isMini 是否接口不同
	 *  true: doudougou
	 *  false: miniProgram
	 */
	request: async function(url, method, postData, isDelay, isForm, hideLoading,isMini = true,isToken = false) {
		//接口请求
		let loadding = false;
		let delayed = null;
		delayed && uni.hideLoading();
		clearTimeout(delayed);
		delayed = null;
		if (!hideLoading) {
			if (isDelay) {
				delayed = setTimeout(() => {
					loadding = true
					uni.showLoading({ title: '加载中...' });
				}, 1000)
			} else {
				loadding = true
				uni.showLoading({ title: '加载中...' });
			}
		}
		let token = getToken();
		let header;
		if (token && url != '/user/codeLogin') {
			header = {
				'content-type': isForm == true ? "application/x-www-form-urlencoded; charset=UTF-8" :
					'application/json; charset=UTF-8',
				'token': token
			}
		} else {
			header = {
				'content-type': isForm == true ? "application/x-www-form-urlencoded; charset=UTF-8" :
					'application/json; charset=UTF-8'
			}
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: isMini == true ? tui.interfaceUrl() + url : tui.interfaceUrls() + url,
				data: postData,
				header: header,
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					if(res.data.code == 200 && res.data.isSuccess){
						resolve(res.data)
					}else{
						uni.showToast({
							title:res.data.msg,
							duration:2000,
							icon:'none',
					});
					}
				},
				fail: (res) => {
					reject(res)
				}
			})
		})
	},


}

export default tui
